<template>
  <n-card title="文件上传" class="max-w-2xl mx-auto mt-10">
    <n-space vertical>
      <n-upload
        v-for="(item, idx) in fileItems"
        :key="idx"
        :accept="item.accept"
        :max="1"
        :show-file-list="true"
        :default-upload="false"
        v-model:file-list="item.fileList"
      >
        <template #default>
          <n-button>{{ item.label }}</n-button>
        </template>
      </n-upload>

      <n-button type="primary" :loading="uploading" @click="handleUpload" :disabled="!canUpload">
        上传文件
      </n-button>
    </n-space>

    <n-divider />
    <n-result
      v-if="uploadedFiles.length > 0"
      status="success"
      title="上传成功"
      :description="uploadedFiles.join(', ')"
    />
  </n-card>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useMessage } from 'naive-ui'
import service from '@/network'

const message = useMessage()
const uploading = ref(false)
const uploadedFiles = ref([])

// 文件类型配置
const fileItems = ref([
  { label: '上传 CFG 文件', accept: '.cfg', key: 'cfg', fileList: [] },
  { label: '上传 DAT 文件', accept: '.dat', key: 'dat', fileList: [] },
  { label: '上传 HDR 文件', accept: '.hdr', key: 'hdr', fileList: [] },
  { label: '上传 DMF 或 INF 文件', accept: '.dmf,.inf', key: 'dmf_or_inf', fileList: [] },
])

// 上传前检查逻辑
const canUpload = computed(() => {
  const cfgOk = fileItems.value[0].fileList.length > 0
  const datOk = fileItems.value[1].fileList.length > 0
  const hdrOk = fileItems.value[2].fileList.length > 0
  const dmfOk = fileItems.value[3].fileList.length > 0 // DMF 或 INF 任一
  return cfgOk && datOk && hdrOk && dmfOk
})

const handleUpload = async () => {
  const formData = new FormData()

  // 收集所有文件
  for (const item of fileItems.value) {
    if (item.fileList.length > 0) {
      formData.append('files', item.fileList[0].file)
    }
  }

  uploading.value = true
  try {
    const res = await service.post('/upload-files', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    uploadedFiles.value = res.data.filenames || []
    message.success('文件上传成功')
  } catch (err) {
    console.error(err)
    message.error('文件上传失败，请重试')
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.max-w-2xl {
  max-width: 600px;
}

.mx-auto {
  margin-left: auto;
  margin-right: auto;
}

.mt-10 {
  margin-top: 2.5rem;
}
</style>
